<template>
  <div class="user-profile">
    <div class="profile-header">
      <UserAvatar 
        :userId="userId" 
        size="large"
        @load="handleAvatarLoad"
        @error="handleAvatarError"
      />
      <div class="user-info">
        <h3>{{ userName }}</h3>
        <p>{{ userEmail }}</p>
        <p>用户ID: {{ userId }}</p>
      </div>
    </div>

    <div class="profile-actions">
      <button @click="showUploadDialog = true" class="upload-btn">
        更换头像
      </button>
    </div>

    <!-- 头像上传对话框 -->
    <div v-if="showUploadDialog" class="upload-dialog">
      <div class="dialog-content">
        <h4>上传新头像</h4>
        <input 
          type="file" 
          accept="image/*" 
          @change="handleFileChange"
          ref="fileInput"
        />
        <div class="dialog-actions">
          <button @click="uploadNewAvatar" :disabled="!selectedFile">
            上传
          </button>
          <button @click="showUploadDialog = false">取消</button>
        </div>
        <div v-if="uploadStatus" class="upload-status">
          {{ uploadStatus }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import UserAvatar from './UserAvatar.vue'
import { createTestUser, uploadImage } from '../api/image'

export default {
  name: 'UserProfile',
  components: {
    UserAvatar
  },
  setup() {
    const userId = ref('')
    const userName = ref('测试用户')
    const userEmail = ref('test@example.com')
    const userAvatarFileName = ref('')
    const showUploadDialog = ref(false)
    const selectedFile = ref(null)
    const uploadStatus = ref('')
    const fileInput = ref(null)

    const handleAvatarLoad = (url) => {
      console.log('头像加载成功:', url)
    }

    const handleAvatarError = (error) => {
      console.log('头像加载失败，使用默认头像')
    }

    const handleFileChange = (event) => {
      selectedFile.value = event.target.files[0]
    }

    const uploadNewAvatar = async () => {
      if (!selectedFile.value) return

      try {
        uploadStatus.value = '上传中...'
        
        // 调试信息
        console.log('开始上传头像...')
        console.log('用户ID:', userId.value)
        console.log('文件信息:', selectedFile.value)
        console.log('文件大小:', selectedFile.value.size)
        console.log('文件类型:', selectedFile.value.type)
        
        // 上传图片
        const formData = new FormData()
        formData.append('file', selectedFile.value)
        formData.append('userId', userId.value)
        formData.append('description', '用户头像')
        formData.append('tags', 'avatar')

        // 调试 FormData
        console.log('FormData 内容:')
        for (let [key, value] of formData.entries()) {
          console.log(key, ':', value)
        }

        const response = await uploadImage(formData)
        
        // 显示成功提示弹窗
        ElMessage.success('头像修改成功！')
        
        // 清空文件选择
        if (fileInput.value) {
          fileInput.value.value = ''
        }
        selectedFile.value = null
        
        // 立即关闭对话框
        showUploadDialog.value = false
        uploadStatus.value = ''
      } catch (error) {
        // 显示错误提示弹窗
        ElMessage.error(`上传失败: ${error.message}`)
        uploadStatus.value = `上传失败: ${error.message}`
        console.error('上传失败:', error)
      }
    }

    onMounted(async () => {
      try {
        // 获取当前登录用户的ID
        const currentUserId = localStorage.getItem('userId')
        if (currentUserId) {
          userId.value = currentUserId
          userName.value = localStorage.getItem('username') || '当前用户'
        } else {
          // 如果没有登录用户，创建测试用户
          const userResponse = await createTestUser()
          userId.value = userResponse.data.userId
          userName.value = userResponse.data.username
        }
      } catch (error) {
        console.error('获取用户ID失败:', error)
      }
    })

    return {
      userId,
      userName,
      userEmail,
      userAvatarFileName,
      showUploadDialog,
      selectedFile,
      uploadStatus,
      fileInput,
      handleAvatarLoad,
      handleAvatarError,
      handleFileChange,
      uploadNewAvatar
    }
  }
}
</script>

<style scoped>
.user-profile {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.profile-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.user-info h3 {
  margin: 0 0 8px 0;
  color: #333;
}

.user-info p {
  margin: 4px 0;
  color: #666;
}

.profile-actions {
  margin-bottom: 20px;
}

.upload-btn {
  padding: 10px 20px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.upload-btn:hover {
  background: #0056b3;
}

.upload-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  padding: 30px;
  border-radius: 8px;
  min-width: 400px;
}

.dialog-content h4 {
  margin: 0 0 20px 0;
  color: #333;
}

.dialog-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.dialog-actions button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.dialog-actions button:first-child {
  background: #007bff;
  color: white;
}

.dialog-actions button:first-child:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.dialog-actions button:last-child {
  background: #6c757d;
  color: white;
}

.upload-status {
  margin-top: 15px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
  font-size: 14px;
  color: #666;
}
</style> 